﻿using BlogDemo.Core.Entities;
using BlogDemo.Core.Interface;
using BlogDemo.Infrastructure.Database;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlogDemo.Infrastructure.Repositories
{
    public class PostRepository
        : IPostRepository
    {
        private readonly BlogContext _ctx;
        private readonly SqlSugarContext _sqlSugarContext;
        public PostRepository(BlogContext ctx, SqlSugarContext sqlSugarContext)
        {
            _ctx = ctx;
            _sqlSugarContext = sqlSugarContext;
        }

        public async Task AddAsync(Post post)
        {
            await _ctx.AddAsync(post);
            //await _sqlSugarContext._client.Deleteable<Post>().Where(p => p.Id >= 0).ExecuteCommandAsync();
            await _sqlSugarContext._client.Insertable<Post>(post).IgnoreColumns(t => new { t.Id }).ExecuteReturnIdentityAsync();
        }

        public async Task<PagedList<Post>> GetAllAsync(string title, int pageIndex, int pageSize, string orderBy)
        {
            var query = _ctx.Post.AsNoTracking();
            if (!string.IsNullOrEmpty(title))
            {
                query = query.Where(p => p.Title.ToLowerInvariant().Equals(title.ToLowerInvariant()));
            }
            query = query
               .OrderBy(p => p.Id);
            return new PagedList<Post>(pageIndex, pageSize, query.Count(), await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync());
        }

        public async Task<Post> GetByIdAsync(int id)
        {
            return await _ctx.Post.SingleOrDefaultAsync(p => p.Id == id);
        }
    }
}
